package com.enation.app.javashop.consumer.shop.trade.consumer;

import com.dag.eagleshop.core.account.model.dto.payment.FreezePrePayReqDTO;
import com.dag.eagleshop.core.account.model.dto.payment.FreezePrePayRespDTO;
import com.dag.eagleshop.core.account.model.enums.AccountTypeEnum;
import com.dag.eagleshop.core.account.model.enums.TradeSubjectEnum;
import com.dag.eagleshop.core.account.service.AccountPaymentManager;
import com.enation.app.javashop.consumer.core.event.TradeIntoDbEvent;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.payment.model.dos.PaymentBillDO;
import com.enation.app.javashop.core.payment.model.enums.PaymentPluginEnum;
import com.enation.app.javashop.core.payment.model.enums.TradeType;
import com.enation.app.javashop.core.payment.service.PaymentBillManager;
import com.enation.app.javashop.core.trade.order.model.dto.OrderDTO;
import com.enation.app.javashop.core.trade.order.model.vo.TradeVO;
import com.enation.app.javashop.core.trade.order.service.OrderQueryManager;
import com.enation.app.javashop.core.trade.sdk.model.OrderDetailDTO;
import com.enation.app.javashop.core.trade.sdk.model.OrderSkuDTO;
import com.enation.app.javashop.framework.database.DaoSupport;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author 王志杨
 * @since 2020/10/20 11:28
 * 生成交易单后含有钱包支付的冻结账户钱包支付的金额
 */
@Component
public class AccountFreezeConsumer implements TradeIntoDbEvent {

    @Autowired
    private PaymentBillManager paymentBillManager;
    @Autowired
    private AccountPaymentManager accountPaymentManager;
    @Autowired
    private MemberManager memberManager;
    @Autowired
    private OrderQueryManager orderQueryManager;
    @Autowired
    @Qualifier("tradeDaoSupport")
    private DaoSupport daoSupport;

    protected final Log logger = LogFactory.getLog(this.getClass());

    @Override
    public void onTradeIntoDb(TradeVO tradeVO) {
        try {
            logger.debug("准备冻结账户钱包金额");
            double walletPayPrice = tradeVO.getWalletPayPrice();
            if (walletPayPrice > 0) {
                String tradeSn = tradeVO.getTradeSn();
                String orderSn = this.daoSupport.queryForString("select sn from es_order where trade_sn = ? LIMIT 0,1", tradeSn);
                PaymentBillDO paymentBill = tradeVO.getPaymentBillDO();
                if (ObjectUtils.isEmpty(paymentBill)) {
                    paymentBill = paymentBillManager.getBillBySnAndTradeTypeAndPaymentPluginID(orderSn,
                            TradeType.order.toString(), PaymentPluginEnum.walletPayPlugin.toString());
                }
                if (paymentBill == null) {
                    throw new RuntimeException("冻结账户钱包金额异常：获取钱包支付单失败");
                }
                Member member = memberManager.getModel(tradeVO.getMemberId());
                if (member == null) {
                    throw new RuntimeException("冻结账户钱包金额异常：获取用户信息失败");
                }

                FreezePrePayReqDTO freezePrePayReqDTO = this.buildFreezePrePayReq(paymentBill, member);

                //拼接交易内容
                freezePrePayReqDTO.setTradeContent("订单号" + orderSn + "交易款项");

                logger.debug("冻结账户钱包金额请求参数准备完毕：" + freezePrePayReqDTO);
                logger.debug("开始冻结账户钱包金额");
                FreezePrePayRespDTO freezePrePayRespDTO = accountPaymentManager.freezePrePay(freezePrePayReqDTO);
                logger.debug("冻结账户钱包金额完毕，返回结果：" + freezePrePayRespDTO);
                if (!freezePrePayRespDTO.isSuccess()) {
                    throw new RuntimeException("冻结账户钱包金额异常：" + freezePrePayRespDTO.getMessage());
                }
            }
        } catch (Exception e) {
            logger.error("冻结账户钱包金额异常：" + e);
        }
    }

    private FreezePrePayReqDTO buildFreezePrePayReq(PaymentBillDO paymentBill, Member member) {
        FreezePrePayReqDTO freezePrePayReqDTO = new FreezePrePayReqDTO();
        freezePrePayReqDTO.setTradeVoucherNo(paymentBill.getOutTradeNo());
        freezePrePayReqDTO.setDraweeMemberId(member.getAccountMemberId());
        freezePrePayReqDTO.setAccountType(AccountTypeEnum.MEMBER_MASTER.getIndex());
        freezePrePayReqDTO.setAmount(BigDecimal.valueOf(paymentBill.getTradePrice()));
        freezePrePayReqDTO.setTradeSubject(TradeSubjectEnum.ORDER_PAYMENT_WALLET.description());
        freezePrePayReqDTO.setOperatorId(member.getMemberId().toString());
        freezePrePayReqDTO.setOperatorName(member.getNickname());
        return freezePrePayReqDTO;
    }
}
